package procsim;

import java.util.*;

public class SignalRegistry {

    private static HashMap<Signal, ArrayList<Integer>> registry = new HashMap<Signal, ArrayList<Integer>>();

    /**
     * Ako nije prisutan, signal se dodaje u registar; u suprotnom, nova vrednost se dodaje u listu za dati signal
     */
    public static void addSignalValue(Signal signal){
        boolean status = false; // false ako nije u registru
        Iterator iter = registry.keySet().iterator();
        while(iter.hasNext() && !status){
            Signal temp = (Signal)iter.next();
            if(temp==signal){
                status = true;
                registry.get(temp).add(signal.get());
            }
        }
        if(!status){
            ArrayList<Integer> values = new ArrayList<Integer>();
            values.add(signal.get());
            registry.put(signal, values);
        }
    }

    public static ArrayList<Signal> getSignals(){
        return new ArrayList<Signal>(registry.keySet());
    }
    
    public static ArrayList<Integer> getValues(Signal signal){
        return getValues(signal.getName());
    }

    public static ArrayList<Integer> getValues(String name){
        boolean status = false;
        Signal temp = null;
        Iterator iter = registry.keySet().iterator();
        while(iter.hasNext() && !status){
            temp = (Signal)iter.next();
            if(temp.getName().equals(name)) status = true;
        }
        if (temp==null)
            System.err.println("Singal nije pronadjen u Registru signala!");
        return registry.get(temp);
   }

    public static ArrayList<String> getNames(){
        ArrayList<String> names = new ArrayList<String>();
        Iterator iter = registry.keySet().iterator();
        while(iter.hasNext()){
            Signal temp = (Signal)iter.next();
            names.add(temp.getName());
        }
        return names;
    }

    public static void update(){
        Iterator iter = getSignals().iterator();
        while(iter.hasNext()){
            addSignalValue((Signal)iter.next());
        }
    }

    public static void updateLastSignals(){
        Iterator iter = getSignals().iterator();
        while(iter.hasNext()){
            Signal sig = (Signal)iter.next();
            ArrayList<Integer> tmp = registry.get(sig);
            tmp.remove(tmp.size()-1);
            addSignalValue(sig);
        }
    }

    public static void emptyRegistry(){
        registry = new HashMap<Signal, ArrayList<Integer>>();
    }
}
